package top.mengchaob.fileserver.netty.busAtomHandler;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.multipart.FileUpload;
import io.netty.util.AttributeKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import top.mengchaob.fileserver.netty.api.FileServiceI;
import top.mengchaob.fileserver.netty.bean.ResultBeanNetty;
import top.mengchaob.fileserver.netty.handler.ParaChannelHandler;
import top.mengchaob.fileserver.netty.table.FileDo;
import top.mengchaob.fileserver.netty.util.FileUtil;
import top.mengchaob.util.PropUtil;
import top.mengchaob.util.SpringCtx;
import top.mengchaob.util.UtilTimeFormatter;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.Set;

/**
 * @title：
 * @author: mengchaob
 * @date: 2021年05月12日 15:42
 * @description:
 */
@Component("updateFileAtomHandler")
@Scope("prototype")
public class UpdateFileAtomHandler  extends ChannelInboundHandlerAdapter {
    private static final Logger logger = LoggerFactory.getLogger(SaveFileAtomHandler.class);
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        FileServiceI fileServiceI = SpringCtx.getApplicationContext().getBean(FileServiceI.class);
        ParaChannelHandler paraChannelHandler = (ParaChannelHandler)ctx.pipeline().get("paraChannelHandler");
        HashMap<String, FileUpload> fileUploads = paraChannelHandler.fileUploads;
        HashMap<String,String> formPara = paraChannelHandler.formaras;
        Set<String> fileuplad = fileUploads.keySet();
        String[] f = new String[fileuplad.size()];
        fileuplad.toArray(f);
        String baseUrl = PropUtil.getV("baseUrl");
        /**
         * lbCode做路径
         */
        String fileUrl = formPara.get("lbCode");
        String type = formPara.get("type");
        String fileId = formPara.get("fileId");
        String fileName = formPara.get("fileName");
        if(fileUrl==null){
            fileUrl="";
        }
        FileDo fileDo= new FileDo();
        fileDo.setCreateTime(UtilTimeFormatter.getTimeToYMDHMS(new Date().getTime()));
        fileDo.setFileId(fileId);
        fileDo.setFileName(fileName);
        fileDo.setLbCode(fileUrl);
        fileDo.setType(type);
        for(int i=0;i<f.length;i++){
            FileUtil.createDir(baseUrl+ File.separator+fileUrl);
            fileDo.setFileName(f[i]);
            //如果已经存在则删除
            String suffix = f[i].substring(f[i].lastIndexOf("."));
            FileUtil.saveByFileUploadAndFileName(fileUploads.get(f[i]),baseUrl+File.separator+fileUrl+File.separator+fileDo.getFileId()+suffix);
        }
        fileServiceI.updateFile(fileDo);
        AttributeKey<ResultBeanNetty> reusltBean = AttributeKey.valueOf("resultBean");
        ResultBeanNetty resultBean = ctx.channel().attr(reusltBean).get();
        resultBean.setErrcode("0");
        resultBean.setMsg("保存成功！");
        ctx.fireChannelRead(msg);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        ctx.pipeline().remove("updateFileAtomHandler");
        logger.debug("channelInactive删除updateFileAtomHandler");
        super.channelInactive(ctx);
    }
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.pipeline().remove("updateFileAtomHandler");
        logger.debug("exceptionCaught删除updateFileAtomHandler");
        super.exceptionCaught(ctx, cause);
    }
}
